const API_BASE_URL = '/api/suppliers';

// DOM 元素
const supplierListSection = document.getElementById('supplier-list');
const createSupplierSection = document.getElementById('create-supplier');
const editSupplierSection = document.getElementById('edit-supplier');
const searchSupplierSection = document.getElementById('search-supplier');
const supplierDetailsSection = document.getElementById('supplier-details');
const suppliersTableBody = document.querySelector('#suppliers-table tbody');
const createSupplierForm = document.getElementById('create-supplier-form');
const editSupplierForm = document.getElementById('edit-supplier-form');
const refreshBtn = document.getElementById('refresh-btn');
const searchByIdBtn = document.getElementById('search-by-id-btn');
const searchByCodeBtn = document.getElementById('search-by-code-btn');
const searchByStatusBtn = document.getElementById('search-by-status-btn');
const editSupplierBtn = document.getElementById('edit-supplier-btn');
const enableSupplierBtn = document.getElementById('enable-supplier-btn');
const disableSupplierBtn = document.getElementById('disable-supplier-btn');
const deleteSupplierBtn = document.getElementById('delete-supplier-btn');
const backBtn = document.getElementById('back-btn');
const backToSupplierListBtn = document.getElementById('back-to-supplier-list');
const backToSupplierListFromDetailBtn = document.getElementById('back-to-supplier-list-from-detail');
const cancelEditBtn = document.getElementById('cancel-edit');

let currentSupplierId = null;

// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
    // 加载供应商列表
    loadSuppliers();
    
    // 导航链接事件监听
    document.querySelector('a[href="index.html"]').addEventListener('click', function(e) {
        e.preventDefault();
        window.location.href = 'index.html';
    });
    
    document.querySelector('a[href="supplier.html"]').addEventListener('click', function(e) {
        e.preventDefault();
        window.location.href = 'supplier.html';
    });
    
    document.querySelector('a[href="#supplier-list"]').addEventListener('click', function(e) {
        e.preventDefault();
        showSection(supplierListSection);
        hideElement(supplierDetailsSection);
    });
    
    document.querySelector('a[href="#create-supplier"]').addEventListener('click', function(e) {
        e.preventDefault();
        showSection(createSupplierSection);
        hideElement(supplierDetailsSection);
    });
    
    document.querySelector('a[href="#search-supplier"]').addEventListener('click', function(e) {
        e.preventDefault();
        showSection(searchSupplierSection);
        hideElement(supplierDetailsSection);
    });
    
    // 刷新按钮事件监听
    refreshBtn.addEventListener('click', loadSuppliers);
    
    // 创建供应商表单提交事件监听
    createSupplierForm.addEventListener('submit', function(e) {
        e.preventDefault();
        createSupplier();
    });
    
    // 编辑供应商表单提交事件监听
    editSupplierForm.addEventListener('submit', function(e) {
        e.preventDefault();
        updateSupplier();
    });
    
    // 搜索按钮事件监听
    searchByIdBtn.addEventListener('click', function() {
        const supplierId = document.getElementById('search-id').value;
        if (supplierId) {
            getSupplierById(supplierId);
        } else {
            alert('请输入供应商ID');
        }
    });
    
    searchByCodeBtn.addEventListener('click', function() {
        const supplierCode = document.getElementById('search-code').value;
        if (supplierCode) {
            getSupplierByCode(supplierCode);
        } else {
            alert('请输入供应商编码');
        }
    });
    
    searchByStatusBtn.addEventListener('click', function() {
        const status = document.getElementById('search-status').value;
        getSuppliersByStatus(status);
    });
    
    // 详情页面按钮事件监听
    backBtn.addEventListener('click', function() {
        showSection(supplierListSection);
        hideElement(supplierDetailsSection);
    });
    
    if (backToSupplierListBtn) {
        backToSupplierListBtn.addEventListener('click', function() {
            showSection(supplierListSection);
            hideElement(searchSupplierSection);
        });
    }
    
    if (backToSupplierListFromDetailBtn) {
        backToSupplierListFromDetailBtn.addEventListener('click', function() {
            showSection(supplierListSection);
            hideElement(supplierDetailsSection);
        });
    }
    
    // 编辑按钮事件监听
    editSupplierBtn.addEventListener('click', function() {
        if (currentSupplierId) {
            showEditForm(currentSupplierId);
        }
    });
    
    // 取消编辑按钮事件监听
    cancelEditBtn.addEventListener('click', function() {
        showSection(supplierListSection);
        hideElement(editSupplierSection);
    });
    
    enableSupplierBtn.addEventListener('click', function() {
        if (currentSupplierId) {
            enableSupplier(currentSupplierId);
        }
    });
    
    disableSupplierBtn.addEventListener('click', function() {
        if (currentSupplierId) {
            disableSupplier(currentSupplierId);
        }
    });
    
    deleteSupplierBtn.addEventListener('click', function() {
        if (currentSupplierId && confirm('确定要删除该供应商吗？')) {
            deleteSupplier(currentSupplierId);
        }
    });
});

// 显示指定的部分，隐藏其他部分
function showSection(section) {
    supplierListSection.classList.add('hidden');
    createSupplierSection.classList.add('hidden');
    editSupplierSection.classList.add('hidden');
    searchSupplierSection.classList.add('hidden');
    supplierDetailsSection.classList.add('hidden');
    
    section.classList.remove('hidden');
}

// 隐藏元素
function hideElement(element) {
    element.classList.add('hidden');
}

// 显示元素
function showElement(element) {
    element.classList.remove('hidden');
}

// 显示编辑表单
function showEditForm(supplierId) {
    fetch(`${API_BASE_URL}/${supplierId}`)
        .then(response => response.json())
        .then(supplier => {
            // 填充表单数据
            document.getElementById('edit-supplier-id').value = supplier.id;
            document.getElementById('edit-supplier-code').value = supplier.supplierCode;
            document.getElementById('edit-supplier-name').value = supplier.supplierName;
            document.getElementById('edit-contact-person').value = supplier.contactPerson;
            document.getElementById('edit-contact-phone').value = supplier.contactPhone;
            document.getElementById('edit-address').value = supplier.address;
            document.getElementById('edit-supplier-status').value = supplier.status;
            document.getElementById('edit-supplier-remark').value = supplier.remark || '';
            
            // 显示编辑表单
            showSection(editSupplierSection);
        })
        .catch(error => {
            console.error('获取供应商信息失败:', error);
            alert('获取供应商信息失败: ' + error.message);
        });
}

// 更新供应商
function updateSupplier() {
    const supplierId = document.getElementById('edit-supplier-id').value;
    const supplierData = {
        id: supplierId,
        supplierCode: document.getElementById('edit-supplier-code').value,
        supplierName: document.getElementById('edit-supplier-name').value,
        contactPerson: document.getElementById('edit-contact-person').value,
        contactPhone: document.getElementById('edit-contact-phone').value,
        address: document.getElementById('edit-address').value,
        status: document.getElementById('edit-supplier-status').value,
        remark: document.getElementById('edit-supplier-remark').value
    };

    fetch(`${API_BASE_URL}/${supplierId}`, {
        method: 'PUT',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(supplierData)
    })
    .then(response => {
        if (!response.ok) {
            throw new Error('更新供应商失败');
        }
        return response.json();
    })
    .then(supplier => {
        alert('供应商更新成功');
        showSection(supplierListSection);
        loadSuppliers();
    })
    .catch(error => {
        console.error('更新供应商失败:', error);
        alert('更新供应商失败: ' + error.message);
    });
}

// 日期时间格式化
function formatDateTime(dateTime) {
    if (!dateTime) return '';
    const date = new Date(dateTime);
    return date.toLocaleString('zh-CN');
}

// 获取状态显示文本
function getStatusText(status) {
    const statusMap = {
        'ACTIVE': '启用',
        'INACTIVE': '禁用'
    };
    return statusMap[status] || status;
}

// 获取状态样式类名
function getStatusClassName(status) {
    return `status-badge status-${status}`;
}

// 加载所有供应商
function loadSuppliers() {
    fetch(API_BASE_URL)
        .then(response => {
            if (!response.ok) {
                throw new Error('网络响应错误');
            }
            return response.json();
        })
        .then(suppliers => {
            renderSuppliersTable(suppliers);
        })
        .catch(error => {
            console.error('加载供应商失败:', error);
            alert('加载供应商失败: ' + error.message);
            // 使用mock数据
            renderSuppliersTable(mockSuppliers);
        });
}

// 渲染供应商表格
function renderSuppliersTable(suppliers) {
    suppliersTableBody.innerHTML = '';
    
    if (!suppliers || suppliers.length === 0) {
        suppliersTableBody.innerHTML = '<tr><td colspan="9" style="text-align: center;">暂无供应商数据</td></tr>';
        return;
    }
    
    suppliers.forEach(supplier => {
        const row = document.createElement('tr');
        row.innerHTML = `
            <td>${supplier.id}</td>
            <td>${supplier.supplierCode}</td>
            <td>${supplier.supplierName}</td>
            <td>${supplier.contactPerson}</td>
            <td>${supplier.contactPhone}</td>
            <td>${supplier.address}</td>
            <td class="${getStatusClassName(supplier.status)}">${getStatusText(supplier.status)}</td>
            <td>${formatDateTime(supplier.createdTime)}</td>
            <td>
                <button class="btn btn-sm btn-primary view-details-btn" data-id="${supplier.id}">查看</button>
            </td>
        `;
        suppliersTableBody.appendChild(row);
    });
    
    // 添加查看详情的事件监听
    document.querySelectorAll('.view-details-btn').forEach(btn => {
        btn.addEventListener('click', function() {
            const supplierId = this.getAttribute('data-id');
            showSection(supplierDetailsSection);
            hideElement(supplierListSection);
            getSupplierById(supplierId);
        });
    });
}

// 创建供应商
function createSupplier() {
    const supplierData = {
        supplierCode: document.getElementById('supplier-code').value,
        supplierName: document.getElementById('supplier-name').value,
        contactPerson: document.getElementById('contact-person').value,
        contactPhone: document.getElementById('contact-phone').value,
        address: document.getElementById('address').value,
        status: document.getElementById('supplier-status').value,
        remark: document.getElementById('supplier-remark').value
    };

    fetch(API_BASE_URL, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(supplierData)
    })
    .then(response => {
        if (!response.ok) {
            throw new Error('创建供应商失败');
        }
        return response.json();
    })
    .then(supplier => {
        alert('供应商创建成功');
        createSupplierForm.reset();
        showSection(supplierListSection);
        loadSuppliers();
    })
    .catch(error => {
        console.error('创建供应商失败:', error);
        alert('创建供应商失败: ' + error.message);
    });
}

// 根据ID获取供应商
function getSupplierById(supplierId) {
    fetch(`${API_BASE_URL}/${supplierId}`)
        .then(response => {
            if (!response.ok) {
                throw new Error('获取供应商失败');
            }
            return response.json();
        })
        .then(supplier => {
            displaySupplierDetails(supplier);
        })
        .catch(error => {
            console.error('获取供应商失败:', error);
            alert('获取供应商失败: ' + error.message);
        });
}

// 根据编码获取供应商
function getSupplierByCode(supplierCode) {
    fetch(`${API_BASE_URL}/code/${supplierCode}`)
        .then(response => {
            if (!response.ok) {
                throw new Error('获取供应商失败');
            }
            return response.json();
        })
        .then(supplier => {
            displaySupplierDetails(supplier);
        })
        .catch(error => {
            console.error('获取供应商失败:', error);
            alert('获取供应商失败: ' + error.message);
        });
}

// 根据状态获取供应商
function getSuppliersByStatus(status) {
    let url = API_BASE_URL;
    if (status !== '') {
        url = `${API_BASE_URL}/status/${status}`;
    }
    
    fetch(url)
        .then(response => {
            if (!response.ok) {
                throw new Error('获取供应商失败');
            }
            return response.json();
        })
        .then(suppliers => {
            renderSuppliersTable(suppliers);
            showSection(supplierListSection);
        })
        .catch(error => {
            console.error('获取供应商失败:', error);
            alert('获取供应商失败: ' + error.message);
        });
}

// 显示供应商详情
function displaySupplierDetails(supplier) {
    currentSupplierId = supplier.id;
    
    document.getElementById('detail-id').textContent = supplier.id;
    document.getElementById('detail-supplier-code').textContent = supplier.supplierCode;
    document.getElementById('detail-supplier-name').textContent = supplier.supplierName;
    document.getElementById('detail-contact-person').textContent = supplier.contactPerson;
    document.getElementById('detail-contact-phone').textContent = supplier.contactPhone;
    document.getElementById('detail-address').textContent = supplier.address;
    document.getElementById('detail-status').textContent = getStatusText(supplier.status);
    document.getElementById('detail-created-time').textContent = formatDateTime(supplier.createdTime);
    document.getElementById('detail-updated-time').textContent = formatDateTime(supplier.updatedTime);
    document.getElementById('detail-remark').textContent = supplier.remark || '';
    
    // 更新状态样式
    const statusElement = document.getElementById('detail-status');
    statusElement.className = '';
    statusElement.classList.add('status-badge', `status-${supplier.status}`);
    
    // 显示/隐藏操作按钮
    if (supplier.status === 'ACTIVE') {
        if (disableSupplierBtn) disableSupplierBtn.disabled = false;
        if (enableSupplierBtn) enableSupplierBtn.disabled = true;
    } else {
        if (disableSupplierBtn) disableSupplierBtn.disabled = true;
        if (enableSupplierBtn) enableSupplierBtn.disabled = false;
    }
    
    showSection(supplierDetailsSection);
}

// 启用供应商
function enableSupplier(supplierId) {
    fetch(`${API_BASE_URL}/${supplierId}/enable`, {
        method: 'PUT'
    })
    .then(response => {
        if (!response.ok) {
            throw new Error('启用供应商失败');
        }
        return response.json();
    })
    .then(supplier => {
        alert('供应商已启用');
        displaySupplierDetails(supplier);
        loadSuppliers();
    })
    .catch(error => {
        console.error('启用供应商失败:', error);
        alert('启用供应商失败: ' + error.message);
    });
}

// 禁用供应商
function disableSupplier(supplierId) {
    fetch(`${API_BASE_URL}/${supplierId}/disable`, {
        method: 'PUT'
    })
    .then(response => {
        if (!response.ok) {
            throw new Error('禁用供应商失败');
        }
        return response.json();
    })
    .then(supplier => {
        alert('供应商已禁用');
        displaySupplierDetails(supplier);
        loadSuppliers();
    })
    .catch(error => {
        console.error('禁用供应商失败:', error);
        alert('禁用供应商失败: ' + error.message);
    });
}

// 删除供应商
function deleteSupplier(supplierId) {
    fetch(`${API_BASE_URL}/${supplierId}`, {
        method: 'DELETE'
    })
    .then(response => {
        if (!response.ok) {
            throw new Error('删除供应商失败');
        }
        return response.json();
    })
    .then(() => {
        alert('供应商已删除');
        showSection(supplierListSection);
        loadSuppliers();
    })
    .catch(error => {
        console.error('删除供应商失败:', error);
        alert('删除供应商失败: ' + error.message);
    });
}

// Mock数据
const mockSuppliers = [
    {
        id: 1,
        supplierCode: 'SUP001',
        supplierName: '华为技术有限公司',
        contactPerson: '张经理',
        contactPhone: '0755-12345678',
        address: '深圳市龙岗区华为总部',
        status: 'ACTIVE',
        createdTime: new Date().toISOString(),
        updatedTime: new Date().toISOString(),
        remark: '主要供应商'
    },
    {
        id: 2,
        supplierCode: 'SUP002',
        supplierName: '小米科技有限公司',
        contactPerson: '李经理',
        contactPhone: '010-87654321',
        address: '北京市海淀区小米科技园',
        status: 'ACTIVE',
        createdTime: new Date().toISOString(),
        updatedTime: new Date().toISOString(),
        remark: '备用供应商'
    },
    {
        id: 3,
        supplierCode: 'SUP003',
        supplierName: '苹果电脑贸易有限公司',
        contactPerson: '王经理',
        contactPhone: '021-12345678',
        address: '上海市浦东新区苹果大厦',
        status: 'INACTIVE',
        createdTime: new Date().toISOString(),
        updatedTime: new Date().toISOString(),
        remark: '国外供应商'
    }
];